import re

from selenium.common import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import locate_with

from pom.basePage import BasePage


class ArticleManage(BasePage):
    t_title = (By.XPATH,'/html/body/div/div/section[3]/div/div/div/div[2]/table/tbody/tr[1]/th[2]')
    sidebar = (By.XPATH, '//*[@id="sidebar-menu"]/li[5]/a/span[1]')
    t_author = (By.XPATH, '/html/body/div/div/section[3]/div/div/div/div[2]/table/tbody/tr[1]/th[3]')
    footer = (By.XPATH, '/html/body/div/footer/a')
    title_locator = locate_with(By.TAG_NAME, "a").below(
                              {t_title[0]: t_title[1]}).to_right_of(
                              {sidebar[0]: sidebar[1]}).to_left_of(
                              {t_author[0]: t_author[1]}).above(
                              {footer[0]: footer[1]})
    title_checkbox = locate_with(By.TAG_NAME, 'input').to_left_of(
                              {t_title[0]: t_title[1]})
    batch_del = (By.ID, 'batchDel')
    checked_boxes = (By.CLASS_NAME,'dataItem')
    total_article_num = (By.XPATH,'/html/body/div/div/section[2]/a[1]')

    def __init__(self,driver,hostname):
        super().__init__(driver)
        self.url = f"http://{hostname}/jpress/admin/article".format(hostname=hostname)

    def goto_article_manage_page(self):
        self.goto_page(self.url)

    def click_article(self,title):
        locator = (By.LINK_TEXT,title)
        self.click(locator)

    def move_to_article(self,title):
        locator = (By.LINK_TEXT,title)
        self.move_to(locator)
    def move_to_title(self):
        self.move_to(self.t_title)
    def click_trash(self):
        locator = (By.LINK_TEXT, "垃圾箱")
        self.click(locator)

    def click_title_checkbox(self):
        self.click(self.title_checkbox)

    def num_of_box_checked(self):
        elements = self.find_elements(self.checked_boxes)
        return  len(elements)

    def get_total_article_num(self):
        total_text = self.get_text(self.total_article_num)
        total_num = int(re.split(r"[()]",total_text)[1])
        return total_num


    def batch_delete(self):
        self.click(self.batch_del)


    def get_article_titles(self):
        res = []
        elements = self.find_elements(self.title_locator)
        for e in elements:
            res.append(e.text)
        print(res)
        return res

    def assert_title_not_exists(self,title):
        titles = self.get_article_titles()
        for t in titles:
            assert t != title















